import axios from 'axios'
import qs from 'qs'
import router from '@/router'
import { removeItem, getItem } from '@/utils/storage'

const instance = axios.create({
  responseType: 'json'
})

// 请求拦截器
instance.interceptors.request.use(async config => {
  // 添加token
  if (!config.headers.common['token']) {
    let userInfo = await getItem('userInfo')
    config.headers.common['token'] = userInfo ? JSON.parse(userInfo).token : ''
  }
  return config
})

// 响应拦截器
instance.interceptors.response.use(async response => {
  // 校验token过期
  if (response.data.status === 401) {
    await removeItem('userInfo')
    router.push('/login')
  }
  return response
})

// params 自定义axios get参数
export const get = (url, params) => {
  let obj = {
    validateStatus: status => status < 500
  }
  return instance.get(url, Object.assign(obj, params))
}

// post data 数据
export const post = (url, data) => {
  return instance.post(url, data)
}

// post 表单 data 数据
export const postForm = (url, data) => {
  let params = qs.stringify(data, { arrayFormat: 'repeat' })
  return instance.post(url, params)
}

// 发送文件
export const postFile = (url, data) => {
  return instance.post(url, data)
}

export default instance
